#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <unistd.h>

// DB9 RS232 pinout, function, and in or out with respect to a DTE (the computer is a DTE):
// 1 DCD, input
// 2 RX, input
// 3 TX, output
// 4 DTR, output
// 5 gnd
// 6 DSR, input
// 7 RTS, output
// 8 CTS, input
// 9 RI, input (sometimes not implemented)

int main(int argc, char *argv[]) {
    int fd, status;
    char *port;
    struct termios tio;

    printf("serial test on %s %d %d\n", argv[1], argv[2], argv[3]);

    port = argv[1];
    fd = open(port, O_RDONLY);
    if (fd == -1) {
        printf("%s open() failed: %s\n", port, strerror(errno));
        return 1;
    }

#if TEST
    tcgetattr(fd, &tio);          /* get the termio information */
    tio.c_cflag &= ~HUPCL;        /* clear the HUPCL bit */
    tcsetattr(fd, TCSANOW, &tio); /* set the termio information */
#endif

    if (ioctl(fd, TIOCMGET, &status) == -1)
        printf("TIOCMGET failed: %s\n", strerror(errno));
    else {
        if (status & TIOCM_CTS)
            fputs("CTS is not set, ", stdout);
        else
            fputs("CTS is set, ", stdout);
        if (status & TIOCM_DSR)
            fputs("DSR is not set", stdout);
        else
            fputs("DSR is set", stdout);
        puts(".");
    }

    if (argv[2]) {
        if ( argv[2][0] == '1' )      /* set the DTR line */
            status &= ~TIOCM_DTR;
        else
            status |= TIOCM_DTR;
    }
    
    if (argv[3]) {
        if ( argv[3][0] == '1' )      /* set the RTS line */
            status &= ~TIOCM_RTS;
        else
            status |= TIOCM_RTS;
    }
    
    ioctl(fd, TIOCMSET, &status); /* set the serial port status */

    close(fd);
    return 0;
}
